package com.huqing.icu.base.redis.client;

import com.huqing.icu.base.redis.config.RedisClientConfig;
import com.huqing.icu.base.redis.config.RedisDeployType;
import com.huqing.icu.exceptions.UnexpectedException;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * @Description Redis集群客户端
 * @Author huqing
 * @Date 2025/1/6 10:09
 **/
@Component
public class ClusterRedisClient {

    @Autowired
    private RedisClientConfig redisClientConfig;

    @Bean
    public JedisCluster getJedisCluster() {
        if (redisClientConfig.getUsed() == RedisDeployType.CLUSTER.getCode()) {
            String[] addrs = redisClientConfig.getClusterAddr().split(",");
            if (ArrayUtils.isEmpty(addrs))
                throw new UnexpectedException("redis addr is empty");

            HostAndPort hostAndPort = null;
            Set<HostAndPort> jedisClusterNodes = new HashSet<>();
            for (String addr : addrs) {
                hostAndPort = new HostAndPort(addr.split(":")[0], Integer.valueOf(addr.split(":")[1]));
                jedisClusterNodes.add(hostAndPort);
            }

            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxTotal(redisClientConfig.getMaxTotal());
            jedisPoolConfig.setMaxIdle(redisClientConfig.getMaxIdLe());
            jedisPoolConfig.setMaxWaitMillis(redisClientConfig.getMaxWaitMillis());
            jedisPoolConfig.setTestOnBorrow(redisClientConfig.isTestOnBorrow());
            jedisPoolConfig.setTestOnReturn(redisClientConfig.isTestOnReturn());
            jedisPoolConfig.setMinIdle(redisClientConfig.getMinIdLe());
            JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, redisClientConfig.getTimeout(), redisClientConfig.getSoTimeout(),
                    redisClientConfig.getMaxAttempts(), redisClientConfig.getPassword(), jedisPoolConfig);
            return jedisCluster;
        }
        //return null;

        //可能由于使用JDK17的原因，这里return null会报错，所以返回一个对象
        HostAndPort hostAndPort = new HostAndPort(redisClientConfig.getClusterAddr(), 6378);
        JedisCluster jedisCluster = new JedisCluster(hostAndPort);
        return jedisCluster;
    }
}
